package com.gdzl_hadoop.common;

import com.gdzl_hadoop.util.JsonUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object ob, Exception arg3)
            throws Exception {

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object ob, ModelAndView model)
            throws Exception {

    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object ob) throws Exception {
        System.out.println("------LoginInterceptor-------");
        // 获取请求的URL
        String url = request.getRequestURI();
        //   System.out.println(url);
        // URL:login.jsp是公开的;这个demo是除了login.jsp是可以公开访问的，其它的URL都进行拦截控制
        // 注意：一些静态文件不能拦截，否则会死循环，知道内存耗尽
        HttpSession session = request.getSession();
        if ((url.indexOf("/login.do") >= 0) || (url.indexOf("/logout.do") >= 0 || session.getAttribute("role") != null)) {
            return true;
        }
        // 不符合条件的给出提示信息，跳转到登录界面,代表会话过期
        //  request.setAttribute("msg", "登录失效，请重新登录！");
        response.getWriter().append(JsonUtils.objectToJson("登录过期，请重新登录！"));
        //request.getRequestDispatcher("/index.jsp").forward(request, response);
        //response.sendRedirect("/login");
        return false;
    }

}
